#include "FreeWayEntry.h"
#include "FreeWayMgr.h"



bool FreeWayEntry::init(int type)
{

    if(type == SERVER)
    {
        sockfd = socket(AF_INET,SOCK_DGRAM, 0);


        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servaddr.sin_port = htons(PORTNUM);
         return bind(sockfd, (sockaddr *) &servaddr, sizeof(servaddr));

    }
    else if(type == CLIENT)
    {
        //servaddr = buildAddr(FreeWayMgr::m_freeWayServerIP.c_str(), SERVERPORT);

        LOG(INFO) << "CLIENT ADDR";
        servaddr.sin_family = AF_INET;



        inet_pton(AF_INET,  FreeWayMgr::m_freeWayServerIP.c_str(), &servaddr.sin_addr);
        servaddr.sin_port = htons(SERVERPORT);
         sockfd = socket(AF_INET,SOCK_DGRAM, 0);
         return true;
    }




}







int FreeWayEntry::fwRecv(char * buf, int len)
{
    int nBytes = 0;

    socklen_t sLen = sizeof(cliaddr);


    nBytes = recvfrom(sockfd, buf, len , 0 , (sockaddr*)&cliaddr, &sLen);

    char * pIP = inet_ntoa(cliaddr.sin_addr);





    return nBytes;
}


int FreeWayEntry::fwSend2Server(const char * buf, int l)
{

        LOG(INFO) << "c 2 s:" << " " << buf;

        /*
        servaddr.sin_family = AF_INET;
        inet_pton(AF_INET, "192.168.171.16", &servaddr.sin_addr);
        servaddr.sin_port = htons(SERVERPORT);
        */
        int nBytes = 0;
        socklen_t slen = sizeof(servaddr);
        nBytes = sendto(sockfd, buf, l, 0 ,(sockaddr *)&servaddr, slen );
        return nBytes;

}

int FreeWayEntry::fwRecv(char * buf, int len, char * ipbuff)
{
    int nBytes = 0;

    socklen_t sLen = sizeof(cliaddr);
    bzero( (void *) &cliaddr, sLen);

    nBytes = recvfrom(sockfd, buf, len , 0 , (sockaddr*)&cliaddr, &sLen);

    char * pIP = inet_ntoa(cliaddr.sin_addr);

    memcpy(ipbuff, pIP, 20);



    return nBytes;

}


int FreeWayEntry::fwSend(char * buff, int len)
{
    int nBytes = 0;

    socklen_t sLen = sizeof(cliaddr);
    nBytes = sendto(sockfd, buff, len , 0, (sockaddr *)&cliaddr, sLen);
    return nBytes;


}

int FreeWayEntry::fwSend(const char * buff, int len)
{
    int nBytes = 0;

    socklen_t sLen = sizeof(cliaddr);
    nBytes = sendto(sockfd, buff, len , 0, (sockaddr *)&cliaddr, sLen);
    return nBytes;


}

struct sockaddr_in FreeWayEntry::buildAddr(const char * ipbuf, int port)
{
    struct sockaddr_in anAddr;
    bzero(&anAddr, sizeof(anAddr));
    anAddr.sin_family = AF_INET;
    anAddr.sin_port = htons(SERVERPORT);
    inet_pton(AF_INET, ipbuf, &anAddr.sin_addr);
    return anAddr;
}


int FreeWayEntry::fwSend(char * sendBuff, int len , struct sockaddr_in * addPtr)
{
    int nBytes = 0;
    socklen_t sLen = sizeof(*addPtr);
    nBytes = sendto(sockfd, sendBuff, len, 0, (sockaddr*)addPtr, sLen);
    return nBytes;

}



